from flask import Blueprint,jsonify
from flask import request
from database import db
import json
bp_goods = Blueprint('goods',__name__)

@bp_goods.route('/')
def Goods():
    sql = """select * from cgoods"""
    res = db.findall(sql)
    return jsonify({'code':200,'list':res})


# 加入购物车
@bp_goods.route('/cartM',methods=['POST','GET'])
def cart():
    if request.method == 'POST':
        data = json.loads(request.data)
        userid = int(data['userid'])
        goodsid = int(data['goodsid'])
        sql = "select * from ccart where userid=%d and goodsid=%d"%(userid,goodsid)
        cart = db.findone(sql)

        if cart:
            count = int(cart['count'])+1
            sql = "update ccart set count=%d where id=%d"%(count,cart['id'])
        else:
            sql = "insert into ccart(userid,goodsid,count) values (%d,%d,%d)"%(userid,goodsid,data['count'])
        try:
            db.insert(sql)
            return jsonify({'code':200})
        except:
            return jsonify({'code':20010})
    return '执行'